﻿
/**
 * 这题提供通过类绑定控制类的接口
 */
using System.Data.SQLite;

namespace ZPeng.CSharpPro.DAL.DataBase
{
    // 定义数据库表的类
    public class ExampleTable
    {
        public int Id { get; set; }
        public string Name { get; set; }
        // 更多属性根据实际数据库表字段添加
    }

    public class SqliteDatabaseManager
    {
        private string connectionString = "Data Source=example.db; Version=3;";

        public void CreateTable()
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = @"CREATE TABLE IF NOT EXISTS ExampleTable (Id INTEGER PRIMARY KEY, Name TEXT);";
                    command.ExecuteNonQuery();
                }
            }
        }

        public void Insert(ExampleTable entry)
        {
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = "INSERT INTO ExampleTable (Name) VALUES (@name);";
                    command.Parameters.AddWithValue("@name", entry.Name);
                    command.ExecuteNonQuery();
                }
            }
        }

        public ExampleTable[] SelectAll()
        {
            var result = new List<ExampleTable>();
            using (var connection = new SQLiteConnection(connectionString))
            {
                connection.Open();
                using (var command = new SQLiteCommand(connection))
                {
                    command.CommandText = "SELECT Id, Name FROM ExampleTable;";
                    using (var reader = command.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            result.Add(new ExampleTable
                            {
                                Id = reader.GetInt32(0),
                                Name = reader.GetString(1)
                            });
                        }
                    }
                }
            }
            return result.ToArray();
        }
    }

    class Test001
    {
        static void RunTest(string[] args)
        {
            var dbManager = new SqliteDatabaseManager();
            dbManager.CreateTable();

            var entry = new ExampleTable { Name = "Test Entry" };
            dbManager.Insert(entry);

            var entries = dbManager.SelectAll();
            foreach (var item in entries)
            {
                Console.WriteLine($"ID: {item.Id}, Name: {item.Name}");
            }
        }
    }
}
